﻿using Common;
using Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Renovation.Models;

namespace Renovation.Controllers
{
    public class OrdersController : Controller
    {
        /// <summary>
        /// 订单列表页面
        /// </summary>
        /// <returns></returns>
        public ViewResult OrdersListView()
        {
            return View();
        }
        /// <summary>
        /// 订单添加页面
        /// </summary>
        /// <returns></returns>
        public ViewResult CreateOrdersView()
        {
            return View();
        }
        /// <summary>
        /// 修改订单页面
        /// </summary>
        /// <returns></returns>
        public ViewResult UpdateOrdersView()
        {
            return View();
        }
        /// <summary>
        /// 打印页面
        /// </summary>
        /// <returns></returns>
        public ViewResult PrintOrder() { 
            return View();
        }
        /// <summary>
        /// 选择材料页面
        /// </summary>
        /// <returns></returns>
        public ViewResult ChooseMaterialView()
        {
            return View();
        }
        /// <summary>
        /// 已选择的材料的列表的页面
        /// </summary>
        /// <returns></returns>
        public ViewResult ChooseMaterialListView()
        {
            return View();
        }
        /// <summary>
        /// 添加订单
        /// </summary>
        /// <returns></returns>
        public APIResultModel CreateOrders(string customerName,string customPhone,string address,decimal area,DateTime startTime, DateTime endTime,string designerId, string remark)
        {
            //参数验证
            if (string.IsNullOrEmpty(customerName))
            {
                return APIResultModel.GetErrorResult("请输入客户姓名");
            }
            if (string.IsNullOrEmpty(customPhone))
            {
                return APIResultModel.GetErrorResult("请输入客户电话");
            }
            //创建数据库上下文类型实例
            MyDbContext dbContext = new MyDbContext();

            //创建订单
            Orders Orders = new Orders();
            Orders.Id = Guid.NewGuid().ToString();
            Orders.CustomerName = customerName;
            Orders.CustomPhone = customPhone;
            Orders.Address = address;
            Orders.Area = area;
            Orders.StartTime = startTime;
            Orders.EndTime = endTime;
            Orders.DesignerId = designerId;
            Orders.Remark = remark;
            Orders.CreateTime = DateTime.Now;

            //向数据集添加
            dbContext.Orders.Add(Orders);
            //保存
            dbContext.SaveChanges();

            return APIResultModel.GetSuccessResult("注册成功");
        }
        /// <summary>
        /// 获取一个订单的数据
        /// </summary>
        /// <returns></returns>
        public APIResultModel GetOrders(string id)
        {
            //创建数据库上下文类型实例
            MyDbContext dbContext = new MyDbContext();

            //查看一条数据
            Orders orders = dbContext.Orders.FirstOrDefault(o => o.Id == id);
            return APIResultModel.GetSuccessResult("成功", orders);
        }
        /// <summary>
        /// 获取多条数据
        /// </summary>
        /// <returns></returns>
        public object GetOrdersList(int page, int limit, string customerName)
        {
            //创建数据库上下文类型实例
            MyDbContext dbContext = new MyDbContext();

            //还没有查询出来的数据集

            //IQueryable<Orders> list = dbContext.Orders.Where(e => e.IsDelete == false);
            //算订单下的总价
            var query = (from o in dbContext.Orders.Where(e => e.IsDelete == false)
                         join om in dbContext.OrdersMaterials
                         on o.Id equals om.OrdersId
                         join m in dbContext.Materials.Where(m => m.IsDelete == false)
                         on om.MaterialId equals m.Id
                         select new
                         {
                             om.OrdersId,
                             om.Number,
                             m.Price
                         }).ToList().GroupBy(g => g.OrdersId).Select(obj => {
                             string OrderId = obj.Key;
                             decimal? Total = obj.ToList().Sum(o=> o.Number * o.Price);
                             return new
                             {
                                 OrderId,
                                 Total
                             };
                         }).ToList();
            
            ////customerName有数据
            //if (!string.IsNullOrEmpty(customerName))
            //{

            //    list = list.Where(e => e.CustomerName.Contains(customerName));
            //}
            
            var res = from o in dbContext.Orders.Where(e => e.IsDelete == false)
                       join e in dbContext.Employees.Where(r => r.IsDelete == false)
                       on o.DesignerId equals e.Id
                       into tempR
                       from ee in tempR.DefaultIfEmpty()
                       select new
                       {
                           o.Id,
                           o.CustomerName,
                           o.CustomPhone,
                           o.Address,
                           o.Area,
                           o.StartTime,
                           o.EndTime,
                           DesignerName = ee.Name
                       };
            //最终的结果
            List<object> list = new List<object>();

            foreach (var item in res)
            {
                //匹配订单id相同的数据
                 var data = query.FirstOrDefault(o=>o.OrderId == item.Id);
                var itemData = new
                {
                    item.Id,
                    item.CustomerName,
                    item.CustomPhone,
                    item.Address,
                    item.Area,
                    item.StartTime,
                    item.EndTime,
                    item.DesignerName,
                    data.Total
                };
                list.Add(itemData);
            }
            //获取一共有多少条数据
            int count = list.Count();
            return APIResultModel.GetSuccessResultForLayui("成功", count, list);

        }

        /// <summary>
        /// 删除一个订单
        /// </summary>
        /// <returns></returns>
        public APIResultModel DeleteOrders(string id)
        {
            //创建数据库上下文类型实例
            MyDbContext dbContext = new MyDbContext();

            //先查询订单
            Orders Orders = dbContext.Orders.FirstOrDefault(r => r.Id == id);

            if (Orders != null)
            {
                //订单存在删除
                Orders.IsDelete = true;
                Orders.DeleteTime = DateTime.Now;
                //保存
                dbContext.SaveChanges();

                return APIResultModel.GetSuccessResult("成功");
            }
            else
            {
                //订单不存在报错
                return APIResultModel.GetErrorResult("失败");
            }


        }
        /// <summary>
        /// 批量删除订单
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public APIResultModel BatchDeleteOrders(List<string> ids)
        {
            //创建数据库上下文类型实例
            MyDbContext dbContext = new MyDbContext();

            foreach (var id in ids)
            {
                //先查询订单是否存在
                Orders Orders = dbContext.Orders.FirstOrDefault(e => e.Id == id);

                if (Orders != null)
                {
                    Orders.IsDelete = true;
                    Orders.DeleteTime = DateTime.Now;
                }
            }
            //保存
            int index = dbContext.SaveChanges();
            return APIResultModel.GetSuccessResult("成功");
        }
        /// <summary>
        /// 修改订单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public APIResultModel UpdateOrders(string id, string customerName, string customPhone, string address, decimal area, DateTime startTime, DateTime endTime, string designerId, string remark)
        {
            //参数验证
            if (string.IsNullOrEmpty(customerName))
            {
                return APIResultModel.GetErrorResult("请输入客户姓名");
            }
            if (string.IsNullOrEmpty(customPhone))
            {
                return APIResultModel.GetErrorResult("请输入客户电话");
            }
            //创建数据库上下文类型实例
            MyDbContext dbContext = new MyDbContext();
            //先查询订单
            Orders Orders = dbContext.Orders.FirstOrDefault(e => e.Id == id);

            if (Orders != null)
            {
                //订单存在修改
                Orders.CustomerName = customerName;
                Orders.CustomPhone = customPhone;
                Orders.Address = address;
                Orders.Area = area;
                Orders.StartTime = startTime;
                Orders.EndTime = endTime;
                Orders.DesignerId = designerId;
                Orders.Remark = remark;
                int index = dbContext.SaveChanges();
                return APIResultModel.GetSuccessResult("成功");
            }
            else
            {
                //订单不存在报错
                return APIResultModel.GetSuccessResult("失败");
            }

        }
        /// <summary>
        /// 订单绑定材料
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="materialId"></param>
        /// <param name="number"></param>
        /// <returns></returns>
        [HttpPost]
        public APIResultModel ChooseMaterial(string orderId,string materialId,int number) 
        {
            //参数验证
            if (string.IsNullOrEmpty(orderId))
            {
                return APIResultModel.GetErrorResult("orderId参数未赋值");
            }
            if (string.IsNullOrEmpty(materialId))
            {
                return APIResultModel.GetErrorResult("materialId参数未赋值");
            }
            if (number < 0) {
                return APIResultModel.GetErrorResult("number参数未赋值");
            }
           
            //创建数据库上下文类型实例
            MyDbContext dbContext = new MyDbContext();
            //判断当前材料是否已经选择
            List<string> materialIdList = dbContext.OrdersMaterials.Where(e=>e.OrdersId == orderId).Select(om => om.MaterialId).ToList();
            if (materialIdList.Contains(materialId))
            {
                return APIResultModel.GetErrorResult("该材料已经选择过了");
            }
            //创建订单材料
            OrdersMaterial ordersMaterial = new OrdersMaterial();
            ordersMaterial.Id = Guid.NewGuid().ToString(); 
            ordersMaterial.OrdersId = orderId;
            ordersMaterial.MaterialId = materialId;
            ordersMaterial.Number = number;
            //添加到数据集
            dbContext.OrdersMaterials.Add(ordersMaterial);
            //保存
            dbContext.SaveChanges();
            return APIResultModel.GetSuccessResult("成功");
        }
        /// <summary>
        /// 获取已经选择的材料列表
        /// </summary>
        /// <returns></returns>
        public object GetChooseMaterialList(int page, int limit, string orderId, string materialsName)
        {
            //创建数据库上下文类型实例
            MyDbContext dbContext = new MyDbContext();

            //还没有查询出来的数据集
            var query = from om in dbContext.OrdersMaterials.Where(om => om.OrdersId == orderId)
                      join o in dbContext.Orders.Where(e => e.IsDelete == false)
                      on om.OrdersId equals o.Id
                      join m in dbContext.Materials.Where(e => e.IsDelete == false)
                      on om.MaterialId equals m.Id
                      select new
                      {
                          om.Id,
                          o.CustomerName,
                          MaterialsName = m.Name,
                          om.Number
                      };
            //有搜索条件筛选条件
            if (!string.IsNullOrEmpty(materialsName)) {
                query = query.Where(e => e.MaterialsName.Contains(materialsName));
            }

            //Skip跳过多少条数据，Take拿多少条数据

            var res = query.Skip((page-1)*limit).Take(limit).Select(e => new
            {
               e.Id,
               e.CustomerName,
               e.MaterialsName,
               e.Number   
            }).ToList();
            //获取一共有多少条数据
            int count = query.Count();
            return APIResultModel.GetSuccessResultForLayui("成功", count, res);

        }
        /// <summary>
        /// 删除一个订单材料的绑定
        /// </summary>
        /// <returns></returns>
        public APIResultModel DeleteOrdersMaterial(string id)
        {
            //创建数据库上下文类型实例
            MyDbContext dbContext = new MyDbContext();

            //先查询订单
            OrdersMaterial OrdersMaterial = dbContext.OrdersMaterials.FirstOrDefault(e => e.Id == id);

            if (OrdersMaterial != null)
            {
                //删除
                dbContext.OrdersMaterials.Remove(OrdersMaterial);
                //保存
                dbContext.SaveChanges();

                return APIResultModel.GetSuccessResult("成功");
            }
            else
            {
                //订单不存在报错
                return APIResultModel.GetErrorResult("失败");
            }


        }
        /// <summary>
        /// 批量删除订单材料的绑定
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public APIResultModel BatchDeleteOrdersMaterial(List<string> ids)
        {
            //创建数据库上下文类型实例
            MyDbContext dbContext = new MyDbContext();

            foreach (var id in ids)
            {
                //先查询订单是否存在
                OrdersMaterial OrdersMaterial = dbContext.OrdersMaterials.FirstOrDefault(e => e.Id == id);

                if (OrdersMaterial != null)
                {
                    dbContext.OrdersMaterials.Remove(OrdersMaterial);
                }
            }
            //保存
            int index = dbContext.SaveChanges();
            return APIResultModel.GetSuccessResult("成功");
        }
        /// <summary>
        /// 获取订单打印页面的数据
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public APIResultModel GetPrintData(string orderId) {
            //参数验证
            if (string.IsNullOrEmpty(orderId))
            {
                return APIResultModel.GetErrorResult("orderId参数未赋值");
            }
            //创建数据库上下文类型实例
            MyDbContext dbContext = new MyDbContext();
            //订单的信息
            Orders orders = dbContext.Orders.FirstOrDefault(o => o.IsDelete == false);

            var list = (from om in dbContext.OrdersMaterials.Where(om=>om.OrdersId == orderId)
                       join m in dbContext.Materials.Where(m=>m.IsDelete == false)
                       on om.MaterialId equals m.Id
                       select new {
                           MaterialName = m.Name,
                           m.Unit,
                           om.Number,
                           m.Price,
                           m.PriceMain,
                           m.PriceArtificial,
                           Total = m.Price * om.Number,
                           m.Remark
                       }).ToList();
            //返回的最终结果
            var res = new
            {
                orders.Area,
                orders.CustomerName,
                orders.CustomPhone,
                OrderDetails = list
            };
            return APIResultModel.GetSuccessResult("成功", res);
        }
    }
}
